#include "EndConnectDestHandlerBase.h"

using namespace std;
using namespace log4cplus;

Logger EndConnectDestHandlerBase::log=GetLogger(LOG4CPLUS_TEXT("EndConnectDestHandlerBase"));

ITransHandler::ExecuteResultCode EndConnectDestHandlerBase::Execute(ClientContext &client,OVERLAPPED *ovl)
{
	unsigned int clienSequenceNo=client.SequenceNo();
	LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Start to send server request data."),clienSequenceNo);

	SOCKET sendSock;
	OVERLAPPED *sendOvl;
	GetSendInfo(client,&sendSock,&sendOvl);

	string *requestStr=AssemblyHttpRequest(client);
	LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Assembly http request data successed."),clienSequenceNo);
	WSABUF *buffer = FillBufferWithHttpRequest(client,requestStr);
	LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Fill http request buffer successed."),clienSequenceNo);
	if(log.isEnabledFor(DEBUG_LOG_LEVEL))
	{
		string dumpData(buffer->buf,buffer->len);
		LogDiffCodeMsg(log,LOG4CPLUS_TEXT("Http request data:\r\n%s"),dumpData);
	}

	delete client.SetCurrentHandler(GetNextHandler());
	::ZeroMemory(sendOvl,sizeof(OVERLAPPED));
	int result=::WSASend(sendSock,buffer,1,NULL,0,sendOvl,NULL);
	int errCode=::WSAGetLastError();
	if(result!=0&&errCode!=WSA_IO_PENDING)
	{
		LOG4CPLUS_ERROR_FMT(log,LOG4CPLUS_TEXT("[Client%d]Begin send http request data failed,error code:%d."),clienSequenceNo,errCode);
		return OnExecuteError(client,sendOvl,ITransHandler::ExecuteFatalError);
	}
	LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Begin send http request data successed."),clienSequenceNo);
	return ITransHandler::ExecuteOK;
}